export const Global = {
  data () {
    return {
      BASE_URL_MOBILE: process.env.VUE_APP_BASE_URL_MOBILE,
      BASE_URL_PC: process.env.VUE_APP_BASE_URL_PC,
      VERSION_MOBILE: process.env.VUE_APP_VERSION_MOBILE,
      VERSION_PC: process.env.VUE_APP_VERSION_PC,
      SERVICE_ORG: process.env.VUE_APP_SERVICE_ORG,
      SERVICE_SITE: process.env.VUE_APP_SERVICE_SITE,
      SERVICE_WECHAT: process.env.VUE_APP_SERVICE_WECHAT,
      SERVICE_KNOWLEDGE: process.env.VUE_APP_SERVICE_KNOWLEDGE,
      SERVICE_SURVEY: process.env.VUE_APP_SERVICE_SURVEY,
      SERVICE_SURVEY_CP: process.env.VUE_APP_SERVICE_SURVEY_CP,
      SERVICE_UPGRADE_SURVEY: process.env.VUE_APP_SERVICE_UPGRADE_SURVEY,
      SERVICE_ADMIN: process.env.VUE_APP_SERVICE_ADMIN,
      SERVICE_SYSTEM: process.env.VUE_APP_SERVICE_SYSTEM,
      SERVICE_INTEGRAL: process.env.VUE_APP_SERVICE_INTEGRAL,
      SERVICE_MEETING: process.env.VUE_APP_SERVICE_MEETING,
      SERVICE_MEETING_CP: process.env.VUE_APP_SERVICE_MEETING_CP,
      SERVICE_PORTAL: process.env.VUE_APP_SERVICE_PORTAL,
      SERVICE_CP: process.env.VUE_APP_SERVICE_CP,
      SERVICE_TENANT: process.env.VUE_APP_SERVICE_TENANT,
      SERVICE_ROLE: process.env.VUE_APP_SERVICE_ROLE,
      SERVICE_SYS: process.env.VUE_APP_SERVICE_SYS,
      SERVICE_FILE: process.env.VUE_APP_SERVICE_FILE
    }
  },
  methods: {
    createUniqueId () {
      return parseInt(Math.random() * 10000000) + ''
    },
    /**
     * @params <Object> options
     * 配置项如下：
     *   containerSelector <String> 外容器的DOM选择器
     *   cardSelector <String> 需要进行瀑布流排布的元素DOM选择器
     *   paddingLeft <Number> 外容器左边距
     *   paddingRight <Number> 外容器右边距
     *   paddingTop <Number> 外容器上边距
     *   paddingBottom <Number> 外容器下边距
     *   distanceX <Number> 卡片横向间距
     *   distanceY <Number> 卡片纵向间距
     *   cardWidth <Number> 卡片的宽度
     *   animation <Boolean> 是否过渡动画
     */
    waterFall (options) {
      let contDOM = document.querySelector(options.containerSelector)
      let cardDOMs = Array.prototype.slice.call(document.querySelectorAll(options.cardSelector))
      if (!contDOM || !cardDOMs[0]) {
        return false
      }
      let paddingLeft = options.paddingLeft || 0
      let paddingRight = options.paddingRight || 0
      let paddingTop = options.paddingTop || 0
      let paddingBottom = options.paddingBottom || 0
      let distanceX = options.distanceX || 0
      let distanceY = options.distanceY || 0
      let cardWidth = options.cardWidth || 280
      contDOM.style.position = 'relative'
      // 获取容器的总宽度
      let contWidth = contDOM.offsetWidth - paddingLeft - paddingRight
      // 获取可展示的列数
      let columns = Math.floor((contWidth + distanceX) / (cardWidth + distanceX))
      let columnHeights = []
      cardDOMs.forEach((card, index) => {
        card.style.position = 'absolute'
        if (options.animation) {
          card.style.transition = 'all ease 0.3s'
        }
        // 第一行
        if (index < columns) {
          card.style.top = paddingTop + 'px'
          card.style.left = paddingLeft + (distanceX + cardWidth) * index + 'px'
          columnHeights.push(card.offsetHeight + paddingTop)
        // 不是第一行
        } else {
          // 获取最小的高度， 确定下一张卡片插入的位置
          let minHeight = columnHeights[0]
          let minIndex = 0
          for (let i = 0; i < columns; i++) {
            if (i > 0) {
              if (columnHeights[i] < columnHeights[i - 1]) {
                minHeight = columnHeights[i]
                minIndex = i
              }
            }
          }
          card.style.top = minHeight + distanceY + 'px'
          card.style.left = paddingLeft + (distanceX + cardWidth) * minIndex + 'px'
          columnHeights[minIndex] += (card.offsetHeight + distanceY)
        }
      })
      // 在所有卡片排布完毕后，将外容器的高度调整为最大的高度
      let maxHeight = columnHeights[0]
      for (let i = 0; i < columns; i++) {
        if (i > 0) {
          if (columnHeights[i] > columnHeights[i - 1]) {
            maxHeight = columnHeights[i]
          }
        }
      }
      contDOM.style.height = paddingTop + paddingBottom + maxHeight - distanceY + 'px'
    },
    linkTo (route) {
      this.$router.push(route)
    },
    replaceRoute (route) {
      this.$router.replace(route)
    },
    // 搜索条件 多滤掉值为undefind、null、''键值对
    filterSearchInfo (obj) {
      let params = {}
      Object.keys(obj).map(item => {
        if (obj[item] !== '' && obj[item] !== undefined && obj[item] !== 'undefined' && obj[item] !== null && obj[item] !== 'null') {
          params[item] = obj[item]
        }
      })
      return params
    },
    // 获取字符串的字符长度
    getCharacterLength (val) {
      let len = 0
      for (let i = 0; i < val.length; i++) {
        let length = val.charCodeAt(i)
        if (length >= 0 && length <= 128) {
          len += 1
        } else {
          len += 2
        }
      }
      return len
    },
    confirm ({ title, tip = '提示', cancelButtonText = '取消', type = 'warning', confirmButtonText = '确定' }) {
      return this.$confirm(title, tip, {
        cancelButtonText,
        confirmButtonText,
        type
      })
    },
    // 格式化时间 YYYY-MM-DD HH:mm:ss
    getFormatedTime (date, split, endType) {
      let _split = split || '-'
      let year = date.getFullYear()
      let month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)
      let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      let minite = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      let second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      if (endType === 'day') {
        return year + _split + month + _split + day
      } else if (endType === 'second') {
        return year + _split + month + _split + day + ' ' + hour + ':' + minite + ':' + second
      } else if (endType === 'hour-minute') {
        return hour + ':' + minite
      } else if (endType === 'hour-second') {
        return hour + ':' + minite + ':' + second
      } else {
        return year + _split + month + _split + day + ' ' + hour + ':' + minite
      }
    },
    showSucc (msg) {
      this.$notify({
        title: '成功',
        message: msg || '操作成功',
        type: 'success'
      })
    },
    showWarning (msg) {
      // this.$notify({
      //   title: '警告',
      //   message: msg || '操作成功',
      //   type: 'warning'
      // })
      this.$message({
        message: msg,
        type: 'warning'
      })
    },
    showErrMsg (msg) {
      this.$notify.error({
        title: '错误',
        message: msg
      })
    },
    showWarnMsg (msg) {
      this.$message({
        type: 'warning',
        message: msg
      })
    },
    showMsg (msg) {
      this.$message.error(msg)
    },
    // 获取字符串的字符长度
    getStringWidth (val) {
      let len = 0
      for (let i = 0; i < val.length; i++) {
        let length = val.charCodeAt(i)
        if (length >= 0 && length <= 128) {
          len += 1
        } else {
          len += 2
        }
      }
      return len
    },
    // 获取cookie
    getCookie (name) {
      let arr = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
      let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
      if (document.cookie.match(reg)) {
        arr = document.cookie.match(reg)
        return unescape(arr[2])
      } else {
        return null
      }
    },
    // 设置cookie
    setCookie (name, value, expiredays) {
      let exdate = new Date()
      exdate.setMinutes(exdate.getMinutes() + expiredays)
      document.cookie = name + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
    },
    // 移除cookie
    removeCookie (name) {
      let exp = new Date()
      exp.setTime(exp.getTime() - 1000)
      let cval = this.getCookie(name)
      if (cval !== null) {
        document.cookie = name + '=' + cval + ';path=/;expires=' + exp.toGMTString()
      }
    },
    // // 获取微信图片
    // getWxImg (img) {
    //   return `http://saas.medchat.yuemia.com/go/relay/picture?wx=${img}`
    // },
    // 获取微信图片
    getWxImg (item) {
      let protocol = document.location.protocol
      if (item && item.startsWith('http://mmbiz.qpic.cn/')) {
        if (/(localhost|172\.29\.95)/.test(location.href)) {
          return protocol + '//test.saas.yuemia.com/' + item.slice(21)
        } else {
          return location.origin + '/' + item.slice(21)
        }
      }
      if (item && item.startsWith('https://mmbiz.qpic.cn/')) {
        if (/(localhost|172\.29\.95)/.test(location.href)) {
          return protocol + '//test.saas.yuemia.com/' + item.slice(22)
        } else {
          return location.origin + '/' + item.slice(22)
        }
      }
      return item
    },
    /**
     * 将外部图片的域名改成微信可访问的域名
     * 问题：公众号图文中外部远程图片不显示
     * 解决方法：配置代理，将域名//statics.xiumi.us改成可信域名
     */
    scrChangeWxSrc (src) {
      let domainXiumi = `//statics.xiumi.us/`
      let domain135 = `//image2.135editor.com/`
      let newDomain = `//www.baidu.com/`
      if (src.indexOf(domainXiumi) >= 0) {
        return this.replaceSrc(src, domainXiumi, newDomain)
      } else if (src.indexOf(domain135) >= 0) {
        return this.replaceSrc(src, domain135, newDomain)
      }
    },
    /**
     * 将外部图片的域名改成企微可访问的域名
     * 问题：企微图文中外部远程图片不显示
     * 解决方法：配置代理，将域名//statics.xiumi.us改成可信域名
     */
    scrChangeCorpSrc (src) {
      let domainXiumi = `//statics.xiumi.us/`
      let domain135 = `//image2.135editor.com/`
      let newDomain = `//www.baidu.com/`
      if (src.indexOf(domainXiumi) >= 0) {
        return this.replaceSrc(src, domainXiumi, newDomain)
      } else if (src.indexOf(domain135) >= 0) {
        return this.replaceSrc(src, domain135, newDomain)
      }
    },
    replaceSrc (src, oldDomain, newDomain) {
      let newSrc = ''
      let tmp = src.split(oldDomain)
      newSrc = tmp[0]
      for (let i = 1; i < tmp.length; i++) {
        newSrc += newDomain + tmp[i]
      }
      return newSrc
    },
    handleError (e) {
      let error = new Error(e.message || e)
      throw error
      // setTimeout(() => {
      //   this.isLoading = false
      // }, 500)
      // let str = e.data + ''
      // if (!window.errTimer) {
      //   window.errTimer = setTimeout(() => delete window.errTimer, 1000)
      //   if (e.response && e.response.data && e.response.data.message) {
      //     this.$notify.error({
      //       title: '错误',
      //       message: e.response.data.message
      //     })
      //   } else {
      //     if (str.search('timeout') !== -1) {
      //       // 超时error捕获
      //       this.$message.error('请求超时,请稍后重试~')
      //     } else if (e.status === 400) {
      //       this.$notify.error({
      //         title: '错误',
      //         message: e.data.message || '无效的请求'
      //       })
      //     } else if (e.status === 403) {
      //       this.$notify.error({
      //         title: '错误',
      //         message: e.data.message || '没有权限'
      //       })
      //     } else if (e.status === 401) {
      //       this.$notify.error({
      //         title: '错误',
      //         message: '未认证'
      //       })
      //     } else if (e.status === 404) {
      //       this.$notify.error({
      //         title: '错误',
      //         message: '找不到服务器，请稍后再试'
      //       })
      //     } else if (e.status === 503) {
      //       this.$notify.error({
      //         title: '错误',
      //         message: '服务暂时无法访问！'
      //       })
      //     } else if (e.status === 5003) {
      //       this.$router.push({name: 'Notfound'})
      //     } else if (e.status === 500) {
      //       this.$notify.error({
      //         title: '错误',
      //         message: e.data.message
      //       })
      //     } else {
      //       let error = new Error(e.message)
      //       throw error
      //     }
      //   }
      // }
    },
    // 消息通知时间格式化
    formatNoticeTime (timeStr) {
      return timeStr.slice(5, 10)
    },
    // 格式化日期(表单填写时用)
    formatDate (val) {
      if (!val) {
        return ''
      }
      let date = new Date(val)
      let year = date.getFullYear()
      let month = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`
      let day = date.getDate() >= 10 ? date.getDate() : `0${date.getDate()}`
      let h = date.getHours() >= 10 ? date.getHours() : `0${date.getHours()}`
      let m = date.getMinutes() >= 10 ? date.getMinutes() : `0${date.getMinutes()}`
      let s = date.getSeconds() >= 10 ? date.getSeconds() : `0${date.getSeconds()}`
      // return `${year}${month}${day}${h}${m}${s}`
      return `${year}-${month}-${day} ${h}:${m}:${s}`
    },
    // 根据传入的格式进行格式化
    formatDatePattern (date, fmt) {
      if (typeof date === 'string') {
        date = new Date(date)
      }
      if (!fmt) fmt = 'yyyy-MM-dd hh:mm:ss'
      if (!date || date == null) return null
      var o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      }
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
      return fmt
    },
    /**
     * 生成随机数
     * @param n 生成随机数位数;
     * @returns {string}
     */
    random (n) {
      const chars = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G',
        'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm',
        'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T',
        't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z'
      ]
      let res = ''
      for (let i = 0; i < n; i++) {
        const id = Math.ceil(Math.random() * 32)
        res += chars[id]
      }
      return res
    },
    // 生成随机数字串
    randomNum (n) {
      let numArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
      let res = '1'
      for (let i = 0; i < n; i++) {
        const id = Math.floor(Math.random() * 10)
        res += numArr[id]
      }
      return res
    },
    // 时间筛选 日期加一天
    addDate (time) {
      var date = new Date(time)
      date.setTime(date.getTime() + 24 * 60 * 60 * 1000)
      let year = date.getFullYear()
      let month = date.getMonth() + 1 >= 10 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`
      let day = date.getDate() >= 10 ? date.getDate() : `0${date.getDate()}`
      return `${year}-${month}-${day}`
    },
    // 根据 target的字段，从origin中更新 target对应的字段
    assignKey (target, origin) {
      if (!target || !origin) {
        return false
      }
      for (let targetKey of Object.keys(target)) {
        if (origin.hasOwnProperty(targetKey)) {
          target[targetKey] = origin[targetKey]
        }
      }
    },
    // dataUrl 转换为 file文件
    dataURLtoFile (dataurl, filename) {
      /* eslint-disable */
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      /* eslint-disable */
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      var type = '.' + (mime.split('/')[1] || '')
      return new File([u8arr], filename + type, { type: mime })
    },
    // 通过文件的链接， 下载文件
    downloadFileByUrl (url, name) {
      let x = new XMLHttpRequest();
      x.open('GET', url, true);
      x.responseType = 'blob';
      x.onload = e => {
        // ie10+
        let defaultName = url.substr(url.lastIndexOf("/") + 1);
        if (navigator.msSaveBlob) {
          return navigator.msSaveBlob(x.response, defaultName);
        } else {
          let link = window.URL.createObjectURL(x.response)
          var a = document.createElement('a');
          a.href = link;
          a.download = name || defaultName;
          a.click();
        }
      }
      x.send();
    },
    // 通过字符编码数值获取对应的存储长度
    // UCS-2编码(16进制) UTF-8 字节流(二进制)    
    // 0000 - 007F       0xxxxxxx （1字节）     
    // 0080 - 07FF       110xxxxx 10xxxxxx （2字节）     
    // 0800 - FFFF       1110xxxx 10xxxxxx 10xxxxxx （3字节）   
    getBytesLength (str) {
      var totalLength = 0;
      var charCode;
      for (var i = 0; i < str.length; i++) {
        charCode = str.charCodeAt(i);
        if (charCode < 0x007f)  {
          totalLength++;
        } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
          totalLength += 2;
        } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
          totalLength += 3;
        } else {
          totalLength += 4;
        }
      }  
      return totalLength;   
    },
    /**
     * 用于 el-cascader 回显
     * @param {Array} tree 数结构数组（有children）
     * @param {String} treeKey 数组中用来匹配的key
     * @param {String} value 用于匹配数组key对应的value
     */
    getParentBgKey(tree, treeKey, value) {
      for (var i in tree) {
        if (tree[i][treeKey] === value) {
          return [tree[i][treeKey]]
        }
        if (tree[i].children && tree[i].children.length > 0) {
          var ro = this.getParentBgKey(tree[i].children, treeKey, value)
          if (ro !== undefined) {
            return ro.concat(tree[i][treeKey])
          }
        }
      }
    },
    /**
     * 用于返回树结构的某个匹配字段的值
     * @param {Array} tree 数结构数组（有children）
     * @param {String} treeKey 数组中用来匹配的key
     * @param {String} value 用于匹配数组key对应的value
     * @param {String} targetKey 用于返回的字段对应的key
     * @param {String} childrenKey 用于指代树结构子孙数组结构的字段key， 默认为'children'
     */
    getTreeValueBgKey(tree, treeKey, value, targetKey, childrenKey='children') {
      for (var i in tree) {
        if (tree[i][treeKey] === value) {
          return tree[i][targetKey]
        }
        if (tree[i][childrenKey] && tree[i][childrenKey].length > 0) {
          let _result = this.getTreeValueBgKey(tree[i][childrenKey], treeKey, value, targetKey)
          if (_result) {
            return _result
          }
        }
      }
    },
    // 编辑文本内容时需要（过滤掉a、class为emoji-img的img以外的标签，过滤掉内联样式）
    filterText (val) {
      // 首先将所有的<div>标签转换称\n， 保持换行
      let str1 = val.replace(/<div>/g, '\n')
      // 过滤a标签以外的标签
      let str2 = str1.replace(/<.*?>/ig, function (tag) {
        if (tag.indexOf('<a href=') === 0 ||
            tag === '</a>' ||
            (tag.indexOf('<img ') === 0) && tag.indexOf('<img class="emoji-img"') === 0) {
          return tag
        } else {
          return ''
        }
      })
      // 过滤内联样式(包括style前方的空格)
      let str3 = str2.replace(/ style\s*?=\s*?(['"])[\s\S]*?\1/g, '')
      // 去除资源协议
      let str4 = str3.replace(/src=(['"])(http|https)?:/g, 'src="')
      // 将&amp;转码为&
      let contStr = str4.replace(/&amp;/g, '&')
      return contStr
    },
    /**
     * @param {Number} number 需要计算的数字
     * @param {Number} count 需要保留的位数
     */
    toNumFixed(number, count) {
      if (!number) return 0
      if (!count) return number
      let stepNum = 10
      for (let i = 1; i < count; i++) {
        stepNum = stepNum * 10
      }
      return (Math.floor(number * stepNum) / stepNum)
    },
    // 随机生成16进制的颜色
    getColor16(){
      var r = Math.floor(Math.random()*256);
      var g = Math.floor(Math.random()*256);
      var b = Math.floor(Math.random()*256);
      var color = '#'+r.toString(16)+g.toString(16)+b.toString(16);
      return color;
    },
    // 根据图表canvas，导出图片，并保证背景是白色
    exportJpgFromCanvas (canvas, imgTitle) {
      let img = new Image()
      img.src = canvas.toDataURL()
      img.onload = () => {
        let newCanvas = document.createElement('canvas')
        newCanvas.width = img.width
        newCanvas.height = img.height
        let context = newCanvas.getContext('2d')
        // 设置背景是白色
        context.fillStyle = '#fff'
        context.fillRect(0, 0, newCanvas.width, newCanvas.height)
        context.drawImage(img, 0, 0)
        // 导出图片
        var picInfo = newCanvas.toDataURL('image/jpeg', 1.0)
        const elink = document.createElement('a')
        elink.download = imgTitle
        elink.style.display = 'none'
        elink.href = picInfo
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      }
    }
  },
  filters: {
    // 资源协议过滤器
    handleResourcePrefix (val, type = 'special') {
      if (!val) {
        return ''
      }
      switch (type) { // 资源协议用当前页访问协议
        case 'special':
          if (val.indexOf('http') < 0) {
            return `${window.location.protocol}${val}`
          } else {
            return val.replace(/^(http|https)?:/, `${window.location.protocol}`)
          }
        case 'default': // 默认去除协议，自动添加
        default:
          return val.replace(/^(http|https)?:/, '')
      }
    }
  }
}

export function queryUrl (key) {
  let name, value
  let str = location.href // 取得整个地址栏
  let num = str.indexOf('?')
  str = str.substr(num + 1) // 取得所有参数
  let arr = str.split('&') // 各个参数放到数组里
  let json = {}
  for (let i = 0; i < arr.length; i++) {
    num = arr[i].indexOf('=')
    if (num > 0) {
      name = arr[i].substring(0, num)
      value = arr[i].substr(num + 1)
      json[name] = value
    }
  }
  return json[key]
}

export const checkForm = {
  methods: {
    // 验证手机号码
    checkTel (tel) {
      let re = /^1\d{10}$/
      return re.test(tel)
    },
    // 验证座机号码 (可带区号)
    checkTel2 (tel) {
      let re = /^([0][1-9]{2,3}-)?[0-9]{5,10}$/
      return re.test(tel)
    },
    // 验证真实姓名
    checkRealName (name) {
      let re = /^[\u4e00-\u9fa5a-zA-Z0-9\s]{0,30}$/
      return re.test(name)
    },
    // 验证工作单位
    checkWorkUnits (workUnit) {
      let re = /^[\u4e00-\u9fa5a-zA-Z0-9()（）]{0,50}$/
      return re.test(workUnit)
    },
    checkUrl (url) {
      let reg = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/
      return reg.test(url)
    },
    checkEmail (email) {
      /* eslint-disable no-useless-escape */
      let re = /\w+((-w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+/
      let result = re.test(email)
      if (result) {
        return true
      } else {
        return false
      }
    },
    checkEmpty (obj) {
      for (let key in obj) {
        if (obj[key] === '') {
          return false
        }
      }
      return true
    }
  }
}

export const emojiConver = {
  data () {
    return {
      // 当前的文本选择范围对象
      currInputRange: null, 
      emojiArr: [
        {code: `/::)`, img: '0.gif', text: '[微笑]'},
        {code: `/::~`, img: '1.gif', text: '[撇嘴]'},
        {code: `/::B`, img: '2.gif', text: '[色]'},
        {code: `/::|`, img: '3.gif', text: '[发呆]'},
        {code: `/:8-)`, img: '4.gif', text: '[得意]'},
        {code: `/::<`, img: '5.gif', text: '[流泪]'},
        {code: `/::$`, img: '6.gif', text: '[害羞]'},
        {code: `/::X`, img: '7.gif', text: '[闭嘴]'},
        {code: `/::Z`, img: '8.gif', text: '[睡]'},
        {code: `/::'(`, img: '9.gif', text: '[大哭]'},
        {code: `/::-|`, img: '10.gif', text: '[尴尬]'},
        {code: `/::@`, img: '11.gif', text: '[发怒]'},
        {code: `/::P`, img: '12.gif', text: '[调皮]'},
        {code: `/::D`, img: '13.gif', text: '[呲牙]'},
        {code: `/::O`, img: '14.gif', text: '[惊讶]'},
        {code: `/::(`, img: '15.gif', text: '[难过]'},
        {code: `/::+`, img: '16.gif', text: '[酷]'},
        {code: `/:--b`, img: '17.gif', text: '[冷汗]'},
        {code: `/::Q`, img: '18.gif', text: '[抓狂]'},
        {code: `/::T`, img: '19.gif', text: '[吐]'},
        {code: `/:,@P`, img: '20.gif', text: '[偷笑]'},
        {code: `/:,@-D`, img: '21.gif', text: '[愉快]'},
        {code: `/::d`, img: '22.gif', text: '[白眼]'},
        {code: `/:,@o`, img: '23.gif', text: '[傲慢]'},
        {code: `/::g`, img: '24.gif', text: '[饥饿]'},
        {code: `/:|-)`, img: '25.gif', text: '[困]'},
        {code: `/::!`, img: '26.gif', text: '[惊恐]'},
        {code: `/::L`, img: '27.gif', text: '[流汗]'},
        {code: `/::>`, img: '28.gif', text: '[憨笑]'},
        {code: `/::,@`, img: '29.gif', text: '[悠闲]'},
        {code: `/:,@f`, img: '30.gif', text: '[奋斗]'},
        {code: `/::-S`, img: '31.gif', text: '[咒骂]'},
        {code: `/:?`, img: '32.gif', text: '[疑问]'},
        {code: `/:,@x`, img: '33.gif', text: '[嘘]'},
        {code: `/:,@@`, img: '34.gif', text: '[晕]'},
        {code: `/::8`, img: '35.gif', text: '[疯了]'},
        {code: `/:,@!`, img: '36.gif', text: '[衰]'},
        {code: `/:!!!`, img: '37.gif', text: '[骷髅]'},
        {code: `/:xx`, img: '38.gif', text: '[敲打]'},
        {code: `/:bye`, img: '39.gif', text: '[再见]'},
        {code: `/:wipe`, img: '40.gif', text: '[擦汗]'},
        {code: `/:dig`, img: '41.gif', text: '[抠鼻]'},
        {code: `/:handclap`, img: '42.gif', text: '[鼓掌]'},
        {code: `/:&-(`, img: '43.gif', text: '[糗大了]'},
        {code: `/:B-)`, img: '44.gif', text: '[坏笑]'},
        {code: `/:<@`, img: '45.gif', text: '[左哼哼]'},
        {code: `/:@>`, img: '46.gif', text: '[右哼哼]'},
        {code: `/::-O`, img: '47.gif', text: '[哈欠]'},
        {code: `/:>-|`, img: '48.gif', text: '[鄙视]'},
        {code: `/:P-(`, img: '49.gif', text: '[委屈]'},
        {code: `/::'|`, img: '50.gif', text: '[快哭了]'},
        {code: `/:X-)`, img: '51.gif', text: '[阴险]'},
        {code: `/::*`, img: '52.gif', text: '[亲亲]'},
        {code: `/:@x`, img: '53.gif', text: '[吓]'},
        {code: `/:8*`, img: '54.gif', text: '[可怜]'},
        {code: `/:pd`, img: '55.gif', text: '[菜刀]'},
        {code: `/:<W>`, img: '56.gif', text: '[西瓜]'},
        {code: `/:beer`, img: '57.gif', text: '[啤酒]'},
        {code: `/:basketb`, img: '58.gif', text: '[篮球]'},
        {code: `/:oo`, img: '59.gif', text: '[乒乓]'},
        {code: `/:coffee`, img: '60.gif', text: '[咖啡]'},
        {code: `/:eat`, img: '61.gif', text: '[饭]'},
        {code: `/:pig`, img: '62.gif', text: '[猪头]'},
        {code: `/:rose`, img: '63.gif', text: '[玫瑰]'},
        {code: `/:fade`, img: '64.gif', text: '[凋谢]'},
        {code: `/:showlove`, img: '65.gif', text: '[嘴唇]'},
        {code: `/:heart`, img: '66.gif', text: '[爱心]'},
        {code: `/:break`, img: '67.gif', text: '[心碎]'},
        {code: `/:cake`, img: '68.gif', text: '[蛋糕]'},
        {code: `/:li`, img: '69.gif', text: '[闪电]'},
        {code: `/:bome`, img: '70.gif', text: '[炸弹]'},
        {code: `/:kn`, img: '71.gif', text: '[刀]'},
        {code: `/:footb`, img: '72.gif', text: '[足球]'},
        {code: `/:ladybug`, img: '73.gif', text: '[瓢虫]'},
        {code: `/:shit`, img: '74.gif', text: '[便便]'},
        {code: `/:moon`, img: '75.gif', text: '[月亮]'},
        {code: `/:sun`, img: '76.gif', text: '[太阳]'},
        {code: `/:gift`, img: '77.gif', text: '[礼物]'},
        {code: `/:hug`, img: '78.gif', text: '[拥抱]'},
        {code: `/:strong`, img: '79.gif', text: '[强]'},
        {code: `/:weak`, img: '80.gif', text: '[弱]'},
        {code: `/:share`, img: '81.gif', text: '[握手]'},
        {code: `/:v`, img: '82.gif', text: '[胜利]'},
        {code: `/:@)`, img: '83.gif', text: '[抱拳]'},
        {code: `/:jj`, img: '84.gif', text: '[勾引]'},
        {code: `/:@@`, img: '85.gif', text: '[拳头]'},
        {code: `/:bad`, img: '86.gif', text: '[差劲]'},
        {code: `/:lvu`, img: '87.gif', text: '[爱你]'},
        {code: `/:no`, img: '88.gif', text: '[NO]'},
        {code: `/:ok`, img: '89.gif', text: '[OK]'},
        {code: `/:love`, img: '90.gif', text: '[爱情]'},
        {code: `/:<L>`, img: '91.gif', text: '[飞吻]'},
        {code: `/:jump`, img: '92.gif', text: '[跳跳]'},
        {code: `/:shake`, img: '93.gif', text: '[发抖]'},
        {code: `/:<O>`, img: '94.gif', text: '[怄火]'},
        {code: `/:circle`, img: '95.gif', text: '[转圈]'},
        {code: `/:kotow`, img: '96.gif', text: '[磕头]'},
        {code: `/:turn`, img: '97.gif', text: '[回头]'},
        {code: `/:skip`, img: '98.gif', text: '[跳绳]'},
        {code: `/:oY`, img: '99.gif', text: '[投降]'},
        {code: `/:#-0`, img: '100.gif', text: '[激动]'},
        {code: `/:hiphot`, img: '101.gif', text: '[乱舞]'},
        {code: `/:kiss`, img: '102.gif', text: '[献吻]'},
        {code: `/:<&`, img: '103.gif', text: '[左太极]'},
        {code: `/:&>`, img: '104.gif', text: '[右太极]'}
      ]
    }
  },
  methods: {
    // 表情code转成图片
    emojiCodeChangeImg (str) {
      // 远端图片地址：//res.wx.qq.com/mpres/htmledition/images/icon/emotion/0.gif
      this.emojiArr.forEach(element => {
        if (str && str.indexOf(element.code) > -1) {
          const effectCode = element.code.replace(/[.\\[\]{}()|^$?*+]/g, '\\$&') // 转义字符串中的元字符
          const pattern = new RegExp(effectCode, 'g')
          // const src = `~assets/img/emoji/${element.img}`
          // const imgUrl = `<img src='${src}'>`
          const imgUrl = `<img class="emoji-img" src="//res.wx.qq.com/mpres/htmledition/images/icon/emotion/${element.img}">`
          str = str.replace(pattern, imgUrl)
        }
      })
      return str
    },
    // 表情text转成图片
    emojiTextChangeImg (str) {
      // 远端图片地址：//res.wx.qq.com/mpres/htmledition/images/icon/emotion/0.gif
      this.emojiArr.forEach(element => {
        if (str && str.indexOf(element.text) > -1) {
          const effectCode = element.text.replace(/[.\\[\]{}()|^$?*+]/g, '\\$&') // 转义字符串中的元字符
          const pattern = new RegExp(effectCode, 'g')
          // const src = `~assets/img/emoji/${element.img}`
          // const imgUrl = `<img src='${src}'>`
          const imgUrl = `<img class="emoji-img" src="//res.wx.qq.com/mpres/htmledition/images/icon/emotion/${element.img}">`
          str = str.replace(pattern, imgUrl)
        }
      })
      return str
    },
    // 图片转成表情code
    imgChangeEmojiCode (str) {
      this.emojiArr.map(element => {
        if (str && str.indexOf(element.img) > -1) {
          const imgUrl = `<img class="emoji-img" src="//res.wx.qq.com/mpres/htmledition/images/icon/emotion/${element.img}">`
          const pattern = new RegExp(imgUrl, 'g')
          str = str.replace(pattern, element.code)
        }
      })
      return str
    },
    // 图片转成表情text
    imgChangeEmojiText (str) {
      this.emojiArr.map(element => {
        if (str && str.indexOf(element.img) > -1) {
          const imgUrl = `<img class="emoji-img" src="//res.wx.qq.com/mpres/htmledition/images/icon/emotion/${element.img}">`
          const pattern = new RegExp(imgUrl, 'g')
          str = str.replace(pattern, element.text)
        }
      })
      return str
    },
    // 点击输入框后，更新当前的选择范围
    updateCurrInputRange (e) {
      // 显示图片间的光标
      if (e.target.tagName.toLowerCase() === 'img') {
        let range = new Range();
        range.setStartBefore(e.target);
        range.collapse(true);
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(range);
      } else if (e.target.tagName.toLowerCase() === 'a') {
        window.eventBus.$emit('previewLink', e)
      }
      let selection = document.getSelection()
      if (selection.rangeCount > 0) {
        // 普通浏览器只支持一个选择范围，所以读取索引为0的range
        this.currInputRange = selection.getRangeAt(0)
      }
    },
    // 插入节点
    insertDOM (dom) {
      // 如果没有选择范围，则不插入节点
      if (!this.currInputRange) {
        return false
      }
      if (this.currInputRange.collapsed) {
        this.currInputRange.insertNode(dom)
      } else {
        this.currInputRange.deleteContents()
        this.currInputRange.insertNode(dom)
      }
      this.currInputRange.collapse(false)
    },
    clearInputRange () {
      this.currInputRange = null
    },
    // 在富文本中给所有<a>标签添加target属性
    addTargetForLink (str, targetType='_blank') {
      let stepStr = str || ''
      // 找出所有的a标签字符串
      let resultArr = stepStr.match(/(<a[^>]+)/g)
      let startIndex = 0
      let endIndex = 0
      let newStr = ''
      if (resultArr && resultArr[0]) {
        for (let i = 0; i < resultArr.length; i++) {
          startIndex = stepStr.indexOf(resultArr[i], endIndex)
          newStr += `${stepStr.slice(endIndex, startIndex)}${resultArr[i]} target='${targetType}'`
          endIndex = startIndex + resultArr[i].length
        }
        newStr += stepStr.slice(endIndex)
      }
      // console.log('newStr: ', newStr)
      return newStr || stepStr
    }
  }
}
